package cc.rengu.igas.share.core.service.channel.upqc;

import cc.rengu.igas.channel.upqc.facade.base.Header;
import cc.rengu.igas.channel.upqc.facade.bean.PayeeInfoBean;
import cc.rengu.igas.channel.upqc.facade.bean.PayerInfo;
import cc.rengu.igas.channel.upqc.facade.bean.RiskInfoBean;
import cc.rengu.igas.channel.upqc.facade.request.B2CQueryCouponRequest;
import cc.rengu.igas.channel.upqc.facade.response.B2CQueryCouponResponse;
import cc.rengu.igas.channel.upqc.facade.result.Result;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.ShareServiceConstant;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.SignAcctInfo;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.ChannelCallModeEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;

import java.util.Objects;

/**
 * UPQC-B2C查询营销
 * Created by lzl on 2021/4/23 11:08
 */
public class B2cQueryCouponService extends ChannelBaseService {
    @Override
    public Object callPreProc(TxnInfo txnInfo, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Header upqcHeader = new Header();
        upqcHeader.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        upqcHeader.setChanlId(channelCallCfg.getMsgSrcId());
        upqcHeader.setSrcSysId(AppParamConstant.SYS_ID);
        upqcHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
        upqcHeader.setVersion(ShareParamConstant.DUBBO_VSERSION);
        upqcHeader.setTxnNum(channelCallCfg.getCallChannelTxn());
        upqcHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + channelCallCfg.getCallIndex());
        upqcHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
        upqcHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
        B2CQueryCouponRequest b2cQueryCouponRequest = new B2CQueryCouponRequest();
        ConvertUtil.convertOutput(b2cQueryCouponRequest);
        b2cQueryCouponRequest.setHeader(upqcHeader);
        SignAcctInfo signAcctInfo = (SignAcctInfo) GlobalTransUtil.getCacheValue(TransCacheConstant.SIGN_ACCT_INFO);
        PayerInfo payerInfo = new PayerInfo();
        UserOrderInfo userOrderInfo = orderInfo.getUserOrderInfo();
        // 付款人员信息
        // 本他行判断
        if ("0".equals(Objects.requireNonNull(signAcctInfo).getSignAcctType().substring(0, 1))) {
            payerInfo.setAccNo(signAcctInfo.getSignAcctNo());
        } else {
            // 他行使用TOKEN
            payerInfo.setAccNo(signAcctInfo.getSignToken());
        }
        // card_hold_name
        payerInfo.setName(signAcctInfo.getCardHoldName());
        // 签约银行名称
        //payerInfo.setPayerBankInfo(signAcctInfo.getSignBankName());
        // 贷记卡判断
        // 01-本行贷记账户
        // 11-他行贷记账户
        if ("01".equals(signAcctInfo.getSignAcctType()) || "11".equals(signAcctInfo.getSignAcctType())) {
            payerInfo.setCardAttr("02"); // 贷记卡
        } else {
            payerInfo.setCardAttr("01"); // 借记卡
        }
        // 预留手机号
        payerInfo.setMobile(signAcctInfo.getReserveMobileNo());
        b2cQueryCouponRequest.setPayerInfo(payerInfo);

        // 银联机构号
        b2cQueryCouponRequest.setIssInsCode(xmlTreeUtil.getXmlTreeStringValue("unonPayCode"));
        // 订单金额	orderAmt --与页面交互，无需除以100
        b2cQueryCouponRequest.setOrderAmt(xmlTreeUtil.getXmlTreeStringValue("txnAmt"));
        //交易顺序号	txnNo
        b2cQueryCouponRequest.setTxnNo(xmlTreeUtil.getXmlTreeStringValue("txnNo"));

        // 收款方信息	payeeInfoBean
        PayeeInfoBean payeeInfoBean = JSON.parseObject(userOrderInfo.getRemark2(), PayeeInfoBean.class);
        b2cQueryCouponRequest.setPayeeInfoBean(payeeInfoBean);

        //风控信息	riskInfo
        RiskInfoBean riskInfo = new RiskInfoBean();
        riskInfo.setDeviceID(xmlTreeUtil.getXmlTreeStringValue("riskInfo/devId"));
        riskInfo.setDeviceName(xmlTreeUtil.getXmlTreeStringValue("riskInfo/deviceMode"));
        riskInfo.setSourceIP(xmlTreeUtil.getXmlTreeStringValue("riskInfo/termIp"));
        riskInfo.setDeviceLocation(xmlTreeUtil.getXmlTreeStringValue("riskInfo/deviceLocation"));
        riskInfo.setDeviceType(xmlTreeUtil.getXmlTreeStringValue("riskInfo/deviceMode"));
        //风控信息	riskInfo
        if (StringUtil.isEmptyOrNull(xmlTreeUtil.getXmlTreeStringValue("riskInfo/devId"))) {
            riskInfo.setDeviceID("DevId");
        } else {
            riskInfo.setDeviceID(xmlTreeUtil.getXmlTreeStringValue("riskInfo/devId"));
        }
        if (StringUtil.isEmptyOrNull(xmlTreeUtil.getXmlTreeStringValue("riskInfo/deviceMode"))) {
            riskInfo.setDeviceName("DeviceMode");
        } else {
            riskInfo.setDeviceName(xmlTreeUtil.getXmlTreeStringValue("riskInfo/deviceMode"));
        }
        if (StringUtil.isEmptyOrNull(xmlTreeUtil.getXmlTreeStringValue("riskInfo/termIp"))) {
            riskInfo.setSourceIP("127.0.0.1");
        } else {
            riskInfo.setSourceIP(xmlTreeUtil.getXmlTreeStringValue("riskInfo/termIp"));
        }
        riskInfo.setDeviceLocation(xmlTreeUtil.getXmlTreeStringValue("riskInfo/deviceLocation"));
        if (StringUtil.isEmptyOrNull(xmlTreeUtil.getXmlTreeStringValue("riskInfo/deviceMode"))) {
            riskInfo.setDeviceType("DeviceType");
        } else {
            riskInfo.setDeviceType(xmlTreeUtil.getXmlTreeStringValue("riskInfo/deviceMode"));
        }
        //应用提供方账户ID
        if (!StringUtil.isEmptyOrNull(userOrderInfo.getUserId())) {
            riskInfo.setAccountIdHash(MD5Util.MD5Encode(userOrderInfo.getUserId()));
        }
        //银行预留手机号
        if (!StringUtil.isEmptyOrNull(signAcctInfo.getReserveMobileNo())) {
            riskInfo.setMobile(signAcctInfo.getReserveMobileNo());
        }
        //账户注册日期  8 位日期字符 yyyymmdd
        if (!StringUtil.isEmptyOrNull(userOrderInfo.getCreateTime())) {
            riskInfo.setUsrRgstrDt(DateUtil.dateStringFormatConvert(userOrderInfo.getCreateTime(), "yyyy-MM-dd HH:mm:ss.SSS", "yyyyMMdd"));
        }

        b2cQueryCouponRequest.setRiskInfo(riskInfo);

        rglog.debug("UPQC B2C查询营销请求:<{}>", JSON.toJSONString(b2cQueryCouponRequest));

        return b2cQueryCouponRequest;
    }

    @Override
    public PayOrderInfo generatePayOrderInfo(ChannelCallCfg channelCallCfg, OrderInfo orderInfo, Object request) throws Exception {
        //此交易不登记支付营销
        return null;
    }

    @Override
    public Object callProc(ChannelCallCfg channelCallCfg, Object request) throws Exception {
        B2CQueryCouponRequest b2cQueryCouponRequest = (B2CQueryCouponRequest) request;
        /* Step1：调用接口，获取结果 */
        Result<B2CQueryCouponResponse> callResult;
        DubboService dubboService = new DubboServiceImpl();
        if (AppParamConstant.YES.equals(channelCallCfg.getSyncCallFlag())) {
            /* Step1.1：异步调用 */
            int iReturnCode;
            int callTimes = 0 == channelCallCfg.getSyncQueryRepeatNum() ? 1 : channelCallCfg.getSyncQueryRepeatNum();
            int gatTime = channelCallCfg.getSyncQueryRepeatTime();
            int gatType = StringUtil.isEmptyOrNull(channelCallCfg.getSyncQueryGapType()) ? 0 : Integer.parseInt(channelCallCfg.getSyncQueryGapType());
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.1：异步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.UPQC_PAYER_SERVICE_INNER_PATH);
                iReturnCode = dubboService.asynCallDubboInnerMethod(clasz, ShareServiceConstant.UPQC_B2C_QUERY_COUPON_METHOD, b2cQueryCouponRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.2：异步远程调用 */
                iReturnCode = dubboService.asynCallDubboService(ShareServiceConstant.UPQC_PAYER_SERVICE, ShareServiceConstant.UPQC_B2C_QUERY_COUPON_METHOD, b2cQueryCouponRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
            if (0 == iReturnCode) {
                return new BizResponse<>(OltpRpcdEnum.TRANS_SUCCESS.getRespCode(), OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            } else {
                return new BizResponse<>(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        } else {
            /* Step1.2：同步调用 */
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.1：同步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.UPQC_PAYER_SERVICE_INNER_PATH);
                callResult = (Result<B2CQueryCouponResponse>) dubboService.callDubboInnerMethod(clasz, ShareServiceConstant.UPQC_B2C_QUERY_COUPON_METHOD, b2cQueryCouponRequest);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.2：同步远程调用 */
                callResult = (Result<B2CQueryCouponResponse>) dubboService.callDubboService(ShareServiceConstant.UPQC_PAYER_SERVICE, ShareServiceConstant.UPQC_B2C_QUERY_COUPON_METHOD, b2cQueryCouponRequest);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
        }
        return callResult;
    }

    @Override
    public Object querySyncCallResult(PayOrderInfo payOrderInfo, Object request) {
        return null;
    }

    @Override
    public OrderInfo callResultOrderProc(OrderInfo orderInfo, String payOrderIndex, TransStatusEnum transStatusEnum, Object response) {
        //此交易不登记营销
        return null;
    }
}
